package controller

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/wonderivan/logger"
	"net/http"
	"teresa/service"
)

var Pod pod

type pod struct{}

func (p *pod) GetNodePods(ctx *gin.Context) {
	params := new(struct {
		FilterName string `form:"filter_name"`
		Limit      int    `form:"limit"`
		Page       int    `form:"page"`
	})
	if err := ctx.Bind(params); err != nil {
		logger.Error("Bind绑定参数失败" + err.Error())
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg":  "bind绑定参数失败" + err.Error(),
			"data": nil,
		})
		return
	}
	data, err := service.Pod.GetNodePods(params.FilterName, params.Limit, params.Page)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"msg":  "获取Node节点上所有pod列表成功",
		"data": data,
	})
}

//获取pod列表，支持分页，过滤，排序
func (p *pod) GetPods(ctx *gin.Context) {

	//处理入参
	//匿名结构体，用于定义入参，get请求为form格式，其他请求为json格式
	params := new(struct {
		FilterName 			string `form:"filter_name"`
		Namespace  			string `form:"namespace"`
		DeploymentName 		string `form:"deploymentname"`
		Limit      			int    `form:"limit"`
		Page       			int    `form:"page"`
	})
	//form格式使用Bind方法,json格式使用ShouldBindJSON方法
	if err := ctx.Bind(params); err != nil {
		logger.Error("Bind绑定参数失败" + err.Error())
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg":  "bind绑定参数失败" + err.Error(),
			"data": nil,
		})
		return
	}
	data, err := service.Pod.GetPods(params.FilterName, params.Namespace,params.DeploymentName, params.Limit, params.Page)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"msg":  "获取pod列表成功",
		"data": data,
	})
}

func (p *pod) GetPodDetail(ctx *gin.Context) {
	//处理入参
	params := new(struct {
		PodName   string `form:"podname"`
		Namespace string `form:"namespace"`
	})
	//form格式使用Bind方法，json格式使用shouldbindjson方法
	if err := ctx.Bind(params); err != nil {
		logger.Error("Bind绑定参数失败" + err.Error())
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg":  "bind绑定参数失败" + err.Error(),
			"data": nil,
		})
		return
	}
	data, err := service.Pod.GetPodDetail(params.PodName, params.Namespace)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	var JsonPodData Jsonpoddata
	jsonpodData, err := json.Marshal(data)
	if err != nil {
		fmt.Println("数据转换失败",err.Error())
		return
	}
	err = json.Unmarshal(jsonpodData, &JsonPodData)
	if err != nil {
		fmt.Println("数据加载失败",err.Error())
		return
	}
	//if err != nil{
	//	fmt.Println("marshal failed")
	//}
	//fmt.Println(string(data1))

	//
	//data1  := `{"spec":"111","status":"222"}`
	//var data1 string = `{"metadata":{"name":"nginx-8567ff84f8-4pmrd","generateName":"nginx-8567ff84f8-","namespace":"default","uid":"c798bcce-e5aa-469c-a310-69802f2f5ade","resourceVersion":"141567","creationTimestamp":"2022-09-12T09:34:15Z","labels":{"app":"nginx","pod-template-hash":"8567ff84f8"},"annotations":{"cni.projectcalico.org/containerID":"c3a4131a7dc4b707c4da900bd049e7db530a8318d80dcb8893351ccc644137af","cni.projectcalico.org/podIP":"192.168.98.97/32","cni.projectcalico.org/podIPs":"192.168.98.97/32"},"ownerReferences":[{"apiVersion":"apps/v1","kind":"ReplicaSet","name":"nginx-8567ff84f8","uid":"17288fca-cb2b-4e83-a9f3-e3099844b680","controller":true,"blockOwnerDeletion":true}],"managedFields":[{"manager":"calico","operation":"Update","apiVersion":"v1","time":"2022-09-12T09:34:15Z","fieldsType":"FieldsV1","fieldsV1":{"f:metadata":{"f:annotations":{".":{},"f:cni.projectcalico.org/containerID":{},"f:cni.projectcalico.org/podIP":{},"f:cni.projectcalico.org/podIPs":{}}}}},{"manager":"kube-controller-manager","operation":"Update","apiVersion":"v1","time":"2022-09-12T09:34:15Z","fieldsType":"FieldsV1","fieldsV1":{"f:metadata":{"f:generateName":{},"f:labels":{".":{},"f:app":{},"f:pod-template-hash":{}},"f:ownerReferences":{".":{},"k:{\\\"uid\\\":\\\"17288fca-cb2b-4e83-a9f3-e3099844b680\\\"}":{".":{},"f:apiVersion":{},"f:blockOwnerDeletion":{},"f:controller":{},"f:kind":{},"f:name":{},"f:uid":{}}}},"f:spec":{"f:containers":{"k:{\\\"name\\\":\\\"main\\\"}":{".":{},"f:image":{},"f:imagePullPolicy":{},"f:name":{},"f:resources":{},"f:terminationMessagePath":{},"f:terminationMessagePolicy":{}}},"f:dnsPolicy":{},"f:enableServiceLinks":{},"f:restartPolicy":{},"f:schedulerName":{},"f:securityContext":{},"f:terminationGracePeriodSeconds":{}}}},{"manager":"kubelet","operation":"Update","apiVersion":"v1","time":"2022-09-12T09:34:17Z","fieldsType":"FieldsV1","fieldsV1":{"f:status":{"f:conditions":{"k:{\\\"type\\\":\\\"ContainersReady\\\"}":{".":{},"f:lastProbeTime":{},"f:lastTransitionTime":{},"f:status":{},"f:type":{}},"k:{\\\"type\\\":\\\"Initialized\\\"}":{".":{},"f:lastProbeTime":{},"f:lastTransitionTime":{},"f:status":{},"f:type":{}},"k:{\\\"type\\\":\\\"Ready\\\"}":{".":{},"f:lastProbeTime":{},"f:lastTransitionTime":{},"f:status":{},"f:type":{}}},"f:containerStatuses":{},"f:hostIP":{},"f:phase":{},"f:podIP":{},"f:podIPs":{".":{},"k:{\\\"ip\\\":\\\"192.168.98.97\\\"}":{".":{},"f:ip":{}}},"f:startTime":{}}}}]}}`
	//
	//json.Unmarshal(data1,&datajson1)
	//fmt.Printf("%+v\n",datajson1)

	ctx.JSON(http.StatusOK, gin.H{
		"msg":  "获取pod详情成功",
		"data": JsonPodData,
	})
}

func (p *pod) DeletePod(ctx *gin.Context) {
	//处理入参
	params := new(struct {
		PodName   string `json:"podname"`
		Namespace string `json:"namespace"`
	})
	fmt.Println(ctx)
	err := ctx.ShouldBindJSON(params)
	if err != nil {
		logger.Error("Bind绑定参数失败" + err.Error())
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg":  "Bind绑定参数失败" + err.Error(),
			"data": nil,
		})
		return
	}
	err = service.Pod.DeletePod(params.PodName, params.Namespace)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"msg":  "删除pod成功",
		"data": nil,
	})
}

func (p *pod) GetPodContainer(ctx *gin.Context) {
	//处理入参
	params := new(struct {
		PodName   string `json:"podname"`
		Namespace string `json:"namespace"`
	})
	err := ctx.ShouldBindJSON(params)
	if err != nil {
		logger.Error("Bind绑定参数失败" + err.Error())
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg":  "Bind绑定参数失败" + err.Error(),
			"data": nil,
		})
		return
	}
	containers, err := service.Pod.GetPodContainer(params.PodName, params.Namespace)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"msg":  "获取containers成功",
		"data": containers,
	})
}

func (p *pod) GetPodLog(ctx *gin.Context) {
	//处理入参
	params := new(struct {
		ContainerName string `form:"containername"`
		PodName       string `form:"podname"`
		Namespace     string `form:"namespace"`
	})
	err := ctx.Bind(params)
	if err != nil {
		logger.Error("Bind绑定参数失败" + err.Error())
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg":  "Bind绑定参数失败" + err.Error(),
			"data": nil,
		})
		return
	}
	data, err := service.Pod.GetPodLog(params.ContainerName, params.PodName, params.Namespace)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg":  err.Error(),
			"data": nil,
		})
	}
	ctx.JSON(http.StatusOK, gin.H{
		"msg":  "获取containers成功",
		"data": data,
	})
}

//获取每个namespace的pod数量
func (p *pod) GetPodNumberNp(ctx *gin.Context) {
	data, err := service.Pod.GetPodNumberNp()
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"msg":  "获取每个namespace的pod数量成功",
		"data": data,
	})

}
